package com.zhentao.user.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.model.common.dtos.ApUser;
import com.zhentao.model.common.dtos.LoginDto;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.user.service.ApUserService;
import com.zhentao.user.mapper.ApUserMapper;
import com.zhentao.utils.common.AppJwtUtil;
import com.zhentao.utils.user.AppThreadLocalUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
* @author EWEWW
* @description 针对表【ap_user(APP用户信息表)】的数据库操作Service实现
* @createDate 2024-05-30 16:01:44
*/
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser>implements ApUserService{
    @Resource
    private ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto apUser) {
        Map<String,Object> map=new HashMap<>();
        //判断账号和密码是否为空
        if(! StringUtils.isEmpty(apUser.getPhone()) || StringUtils.isEmpty(apUser.getPassword())){
//            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"手机或密码为空");
            //验证用户是否存在：查询数据库
            LambdaQueryWrapper<ApUser> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone,apUser.getPhone()).eq(ApUser::getName,apUser.getPassword());
            ApUser apUser1=this.apUserMapper.selectOne(wrapper);
            ApUser apUser2 = new ApUser();
            apUser2.setId(apUser1.getId());
            AppThreadLocalUtil.setUser(apUser2);
            if(Objects.isNull(apUser1)){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"手机或密码错误");
            }
            //判断密码+盐是否正确
            String pwd=apUser.getPassword();
            String salt=apUser1.getSalt();
            pwd= DigestUtils.md5DigestAsHex((pwd+salt).getBytes());
            if(!pwd.equalsIgnoreCase(apUser1.getPassword())){
                return ResponseResult.errorResult( AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            //生成token
            String token= AppJwtUtil.getToken(apUser1.getId().longValue());
            map.put("token", token);
            //把盐和密码置空（安全）
            apUser1.setSalt("");
            apUser1.setPassword("");
            map.put("user", apUser1);
            //返回token令牌
            return ResponseResult.okResult(map);
        }else{
            //2.游客  同样返回token  id = 0
            Map<String, Object> kk = new HashMap<>();
            kk.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }

    }
}




